package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.exception.OrderDisabledException;
import com.itheima.exception.OrderFullException;
import com.itheima.exception.OrderNotAllowedException;
import com.itheima.exception.OrderRepeatedException;
import com.itheima.service.OrderService;
import com.itheima.service.SetmealService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.SMSUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.*;

@RestController
@RequestMapping("/orderSettingList")
public class OrderSettingListController {

    @Reference
    private OrderService orderService;
    @Reference
    private SetmealService setmealService;


    //添加预约
    /*
    此时传入的数据包括会员的基本信息,和预约套餐的id(setmealIds)
    (其中基本信息还包括了预约时间，创建了MemberOrder类接收)
    */
    @RequestMapping("/add")
    //添加预约(多个)
    public Result add(@RequestBody Map<String,Object> map, String[] setmealIds) throws ParseException {


        //由于前台的日期控件没加时间限制，所有再这里要对预约时间加以限制
        String orderDate = (String) map.get("orderDate");
        boolean flag = DateUtils.isInTwoMonths(orderDate);
        if(!flag){
            //此时预约时间超出两个月，或着在今天之前
            return new Result(false,MessageConstant.ORDER_INTWOMONTHS_FAIL);
        }

        //判断是否选中检查套餐
        if(setmealIds == null || setmealIds.length <= 0){
            return new Result(false, MessageConstant.ORDER_ISNULL);
        }

        //掉用service层方法,预约多个套餐
        try {
            orderService.orderMany(map, setmealIds);

        }catch (Exception e) {
            //获取到出错的套餐名称
            //String errorSetmealName = e.getMessage();
            if(e instanceof OrderNotAllowedException){
                //如果是自定义的未进行预约设置的异常
                return new Result(false,e.getMessage()+MessageConstant.SELECTED_DATE_CANNOT_ORDER);
            }
            if(e instanceof OrderFullException){
                return new Result(false,e.getMessage()+MessageConstant.ORDER_FULL);
            }
            if(e instanceof OrderRepeatedException){
                return new Result(false,e.getMessage()+MessageConstant.HAS_ORDERED);
            }
            //如果不是自定义的异常
            return new Result(false,MessageConstant.ORDER_FAIL);
        }

        //此时预约全部成功，此处发送短信代码
        String phoneNumber = (String) map.get("phoneNumber");
        //控制台打印发送消息
        System.out.println("给"+phoneNumber+"发送短信：预约成功");
        /*try {
            String phoneNumber = (String) map.get("phoneNumber");
            //控制台打印发送消息
            System.out.println("给"+phoneNumber+"发送短信：预约成功");
            SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,phoneNumber,"");
        } catch (ClientException e) {
            e.printStackTrace();
        }*/

        //如果预约的所有套餐全部预约成功，才会走到这里
        return new Result(true,MessageConstant.ORDER_SUCCESS);
    }


    //按照条件分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        //直接调用service层方法查询订单
        try {
            //直接调用service层方法查询订单(返回类型时page，继承list，包括了查询到的数据和总条数)
            PageResult pageResult = orderService.findPage(queryPageBean);
            return pageResult;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    //取消预约(单个)
    @RequestMapping("/cancel/{id}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result cancelOrder(@PathVariable Integer id){

        //根据预约id，查询用户手机号
        Map orderDetail = orderService.findById(id);
        String phoneNumber = (String) orderDetail.get("phoneNumber");

        //获取到要取消的预约的id
        try {
            //调用service层方法，取消预约
            orderService.cancelById(id);
        } catch (Exception e) {
            if(e instanceof OrderDisabledException){
                //如果是service中的自定义异常
                return new Result(false,e.getMessage()+MessageConstant.CANCEL_ORDER_DISABLED);
            }
            return new Result(false,MessageConstant.CANCEL_ORDER_FAIL);
        }

        //此时取消预约成功，此处发送短信代码
        //控制台答应发送消息
        System.out.println("给"+phoneNumber+"发送短信：取消预约成功");
        /*
        try {
            //控制台答应发送消息
            System.out.println("给"+phoneNumber+"发送短信：取消预约成功");
            //SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,phoneNumber,"");
        } catch (ClientException e) {
            e.printStackTrace();
        }
        */

        //此时预约成功，发送短信
        return new Result(true,MessageConstant.CANCEL_ORDER_SUCCESS);
    }



    //批量取消预约
    @RequestMapping("/cancelChecked")
    public Result cancelCheckedOrder(Integer[] orderIds){
        //测试获取前台传入的数据是否正确
        System.out.println(Arrays.toString(orderIds));

        //对传入的数据进行判断
        if(orderIds == null || orderIds.length==0){
            return new Result(false,MessageConstant.CHECK_CANCEL_ORDER_ISNULL);
        }

        //存放取消预约的所有手机号
        Set<String> set = new HashSet<>();

        for (Integer orderId : orderIds) {
            //根据预约id，查询用户手机号
            Map orderDetail = orderService.findById(orderId);
            String phoneNumber = (String) orderDetail.get("phoneNumber");
            set.add(phoneNumber);
        }

        try {
            orderService.cancelByIds(orderIds);
        }catch (Exception e){
            if(e instanceof OrderDisabledException){
                //如果是service中的自定义异常
                return new Result(false,e.getMessage()+MessageConstant.CANCEL_ORDER_DISABLED);
            }
            //捕获到的不是自定义的异常
            return new Result(false,MessageConstant.CANCEL_ORDER_FAIL);
        }

        //此时全部取消预约成功，此处发送短信代码
        //此时set集合中就就放的是所有取消预约成功的手机号(不重复)
        for (String phoneNumber : set) {
            //给所有取消预约的用户发送短信
            System.out.println("给"+phoneNumber+"发送短信：取消预约成功");
            //实际发送模板的问题，导致发送失败
            //SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,phoneNumber,"");
        }
        /*try {

            //此时set集合中就就放的是所有取消预约成功的手机号(不重复)
            for (String phoneNumber : set) {
                //给所有取消预约的用户发送短信
                System.out.println("给"+phoneNumber+"发送短信：取消预约成功");
                //实际发送模板的问题，导致发送失败
                //SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,phoneNumber,"");
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }*/
        //此时走到这里，说明选中的全部取消预约成功，发送短信
        return new Result(true,MessageConstant.CANCEL_ORDER_SUCCESS);
    }


    //确认到诊预约
    @RequestMapping("/confirm/{id}")
    public Result confirmOrder(@PathVariable Integer id){
        //获取到要取消的预约的id
        try {
            //调用service层方法，取消预约
            Result result = orderService.confirmById(id);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.CONFIRM_ORDER_FAIL);
        }

    }
}
